package com.kiwilss.aopdemo

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.lifecycle.observe
import androidx.recyclerview.widget.GridLayoutManager
import androidx.work.Constraints
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import com.kiwilss.aopdemo.adapter.MainAdapter
import com.kiwilss.aopdemo.ui.workmanager.TestWorker
import com.kiwilss.aopdemo.utils.DataUtils
import com.kiwilss.aopdemo.utils.LogUtils
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private val mAdapter by lazy {
        MainAdapter()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        rvMainList?.run {
            layoutManager = GridLayoutManager(context, 4)
            adapter = mAdapter
        }
        mAdapter.setList(DataUtils.getDataList())
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val mainBean = mAdapter.data[position]
            startActivity(Intent(this, mainBean.aClass))
        }

        //测试worker manager
        btnMainWorker.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                testWorker()
            }
        }
        btnMainWorkerCancel.setOnClickListener {
            val workRequest = OneTimeWorkRequest.Builder(TestWorker::class.java)
                .build()
            WorkManager.getInstance(this).cancelWorkById(workRequest.id)
        }
        btnMainToast.setOnClickListener {
            LogUtils.toast("test")
        }
    }

    @SuppressLint("IdleBatteryChargingConstraints")
    @RequiresApi(Build.VERSION_CODES.M)
    private fun testWorker() {
        //设置任务约束条件
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
//            .setRequiresCharging(true)
//            .setRequiresDeviceIdle(true)
            .build()
        val workRequest = OneTimeWorkRequest.Builder(TestWorker::class.java)
            .setConstraints(constraints)
            .build()
        //执行
        WorkManager.getInstance(this).enqueue(workRequest)
        //监听状态
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(workRequest.id)
            .observe(this) {
                LogUtils.e( it?.state?.name,"TestWorker")
                if (it?.state!!.isFinished) {
                    LogUtils.e("Finish","TestWorker")
                }
            }
    }
}